package com.im.config;

import com.im.pojoClass.Result;
import com.im.pojoClass.ResultCode;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常捕获处理
 * Created by macro on 2020/2/27.
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 请求缺少参数，或是多了参数
     */
    @ResponseBody
    @ExceptionHandler(value = MissingServletRequestParameterException.class)
    public Result missingServletRequestParameterException(MissingServletRequestParameterException e) {
        e.printStackTrace();
        return new Result(ResultCode.FAILED, "参数错误");
    }

    /**
     * GET和POST混淆使用
     */
    @ResponseBody
    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    public Result httpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        e.printStackTrace();
        return new Result(ResultCode.FAILED, "方法请求类型错误");
    }

    /**
     * 接口参数数据不符合
     */
    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidException(MethodArgumentNotValidException e) {
        e.printStackTrace();
        return new Result(ResultCode.VALIDATE_FAILED, "接口参数校验失败");
    }

    /**
     * Content-type类型错误
     */
    @ResponseBody
    @ExceptionHandler(value = HttpMediaTypeNotSupportedException.class)
    public Result httpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e) {
        e.printStackTrace();
        return new Result(ResultCode.VALIDATE_FAILED, "Content-type类型错误");
    }

    /**
     * 全局错误
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Result exception(Exception e) {
        e.printStackTrace();
        return new Result(ResultCode.FAILED, "服务器错误");
    }
}
